<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket</title>
    <script type="text/javascript" src="${baseUrlRoot}/static/common/script/yehun.socket.js"></script>
    <script type="text/javascript">
        var socket = new YehunSocket();
        socket.create("ws://localhost:8201/cms/spring-websocket");
    </script>
</head>
<body>
    ${message}:
    <input id="text" type="text"/>
    <select id="userId" name="userId"></select>
    <button onclick="send()">发送消息</button>
    <hr/>
    <button id="socket-base-switch" data-flag="1">开启WebSocket连接</button>
    <button id="socket-spring-switch" data-flag="1">开启SpringWebSocket连接</button>
    <hr/>
    <div id="message"></div>

    <script type="text/javascript">
        var webSocket = null;
        var base_url = "ws://" + window.location.host + "/cms/websocket";
        var spring_url = "ws://" + window.location.host + "/cms/spring-websocket";

        //判断当前浏览器是否支持WebSocket
        function createWebSocket(url) {
            if ('WebSocket' in window) {
                webSocket = new WebSocket(url);
            } else if ('MozWebSocket' in window) {
                webSocket = new MozWebSocket(url);
            } else {
                alert('当前浏览器 Not support websocket');
                return false;
                //webSocket = new SockJS("http://localhost:8201/cms/websocket");
            }

            //连接发生错误的回调方法
            webSocket.onerror = function () {
                setMessageInnerHTML("WebSocket连接发生错误");
            };

            //连接成功建立的回调方法
            webSocket.onopen = function () {
                setMessageInnerHTML("WebSocket连接成功");
            };

            //接收到消息的回调方法
            webSocket.onmessage = function (event) {
                onMessage(event.data);
            };

            //连接关闭的回调方法
            webSocket.onclose = function () {
                setMessageInnerHTML("WebSocket连接关闭");
            };
            return true;
        }

        //将消息显示在网页上
        function onMessage(data) {
            console.log(data);
            var json = eval("(" + data + ")");
            switch (json.type) {
                case 0:
                case -1:
                    document.getElementById('message').innerHTML += json.data + '<br/>';
                    break;
                case 1:
                    var select = document.getElementById("userId");
                    var childs = select.childNodes;
                    for (var i = 0; i < childs.length; i++) {
                        select.removeChild(childs[i]);
                    }
                    var option = document.createElement("option");
                    option.value = 0;
                    option.innerText = "全部";
                    select.appendChild(option);
                    var userIds = json.data;
                    for (i = 0; i <= userIds.length; i++) {
                        if (userIds[i] !== undefined && userIds[i] !== "") {
                            console.log("userId=" + userIds[i]);
                            option = document.createElement("option");
                            option.value = userIds[i];
                            option.innerText = userIds[i];
                            select.appendChild(option);
                        }
                    }
                    //document.getElementById('message').innerHTML += json.message + '<br/>';
                    break;
            }
        }

        //将消息显示在网页上
        function setMessageInnerHTML(data) {
            document.getElementById('message').innerHTML += data + '<br/>';
        }

        //关闭WebSocket连接
        function closeWebSocket() {
            if (webSocket !== null) {
                webSocket.close();
                webSocket = null;
            }
        }

        //发送消息
        function send() {
            var inputText = document.getElementById("text");
            var message = inputText.value;
            if (message === undefined || message.trim() === "") {
                alert("请输入要发送的消息");
                return false;
            }
            var userId = document.getElementById("userId").value;
            if (webSocket === null) {
                alert("webSocket未初始化");
                return false;
            }
            try {
                var json = '{ "message": "' + message + '" ';
                if (userId !== "0") {
                    json += ',"userId": "' + userId + '"';
                }
                json += '}';
                webSocket.send(json);
                inputText.value = "";
            } catch (e) {
                alert(e);
            }
        }

        function buttonEvent(obj, url, buttonValue) {
            var attributeName = "data-flag";
            var flag = obj.getAttribute(attributeName) === "1";
            if (flag) {
                if (createWebSocket(url)) {
                    obj.innerText = "关闭" + buttonValue;
                    obj.setAttribute(attributeName, 0);
                }
            } else {
                closeWebSocket();
                obj.innerText = "开启" + buttonValue;
                obj.setAttribute(attributeName, 1);
            }
        }

        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function () {
            closeWebSocket();
        };
        document.getElementById("socket-base-switch").addEventListener("click", function () {
            buttonEvent(this, base_url, "WebSocket连接");
        });
        document.getElementById("socket-spring-switch").addEventListener("click", function () {
            buttonEvent(this, spring_url, "SpringWebSocket连接");
        });
    </script>
</body>
</html>